package com.zjl.legendary.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author zhoujingluo
 * @date 2021/6/14 20:18
 */
@Controller
@RequestMapping("/api/file")
public class FileController {

    @RequestMapping("/getModel.do")
    public String getModel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求下载的文件名
        String fileName = req.getParameter("file");
        //设置响应头
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //获取供用户下载文件的文件夹的真实路径
        String downloadPath = req.getServletContext().getRealPath("/WEB-INF/file");
        //将本地文件读取到流中
        FileInputStream fis= new FileInputStream(downloadPath+"/"+fileName);
        //获取响应输出流
        ServletOutputStream os = resp.getOutputStream();
        //边读边写，供用户下载文件
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = fis.read(buffer)) != -1){
            os.write(buffer,0,count);
        }
        //下载完毕关闭流
        os.close();
        fis.close();
        //用户下载完模板之后重定向到上传文件页面
        return "redirect:/questionupload.jsp";
    }
}
